<template>
  <!-- 添加或修改题库管理对话框 -->
  <el-dialog :title="title" v-model="open" width="960px" append-to-body :destroy-on-close="true">
    <div class="question__form">
      <div class="question__form-left">
        <div class="question__form-title-wrapper">
          <span class="question__form-symbol">*</span>
          <span class="question__form-title">题目类型</span>
        </div>

        <div class="question__form-select-wrapper">
          <div v-for="(name, index) in questionTypeMap" :key="index" @click="changeType(index)" :class="{
            'question__form-select-tag-active':
              `${form.questionType}` === `${index}`,
          }" class="question__form-select-tag">
            <img class="question__form-select-icon" :src="getImageUrl(false, index)" />
            <span>{{ name }}</span>
          </div>
        </div>
      </div>
      <div class="question__form-right">
        <p class="question__form-right-title">{{ getQuestionType(form) }}</p>
        <el-form label-width="80px" ref="questionRef" :model="form" :rules="rules">
          <el-form-item label="标题" prop="questionTitle">
            <el-input v-model="form.questionTitle" :rows="2" type="textarea" placeholder="请输入题目标题" />
          </el-form-item>
          <!-- 切换 -->
          <el-tabs v-if="form.questionType != '1'" v-model="activeAnswerTab" @tab-change="handleTabChange" type="card"
            class="demo-tabs" editable @edit="handleTabsEdit">
            <template #add-icon>
              <el-icon><Select /></el-icon>
            </template>
            <el-tab-pane v-for="item in answerTab" :key="item" :label="`答案${item}`" :name="item"></el-tab-pane>
          </el-tabs>
          <el-form-item label="答案" required>
            <AnswerForm ref="AnswerFormRef" :answer="currentAnswer" :questionType="form.questionType"
              @update="handleAnswerUpdate" />
            <div class="question__button" @click="addQuestionItem()">
              <el-button :icon="Plus">添加选项</el-button>
            </div>
          </el-form-item>
          <el-form-item label="解析" prop="parseContent">
            <el-input v-model="form.parseContent" :rows="2" type="textarea" placeholder="请输入题目解析" />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer" style="display: flex;align-items: center;justify-content: space-between;">
        <div>
          <el-button type="primary" @click="handleImport" v-hasPermi="['examination:question:import']">批量录入</el-button>
        </div>
        <div>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="CouseTime">
import { addpractise, updatepractise } from '@/api/course/practise'
import { Plus, Select } from "@element-plus/icons-vue";
import { ElMessage } from 'element-plus';
import {
  question1,
  question2,
  questionType1,
  questionType2,
} from "../assets/images";
import AnswerForm from "../components/AnswerForm";
import { computed, watch } from 'vue';
const { proxy } = getCurrentInstance();
const emits = defineEmits(['update:visible', 'finish'])
const props = defineProps({
  typeId: {
    type: String,
    default: ''
  },
  practiseType:{
    type: String,
    default: ''
  },
  title: {
    type: String,
    default: ''
  },
  visible: {
    type: Boolean,
    default: false
  },
  detail: {
    type: Object,
    default: new Object()
  }
})
const open = computed({
  get: () => props.visible,
  set: (value) => {
    emits('update:visible', value)
  }
});
const data = reactive({
  form: {
    questionType: '1',
    practiseType: '', //练习类型：c-章节 z-专项类别 k-历年考试
    typeId: null, //相关业务ID，分为章节ID，类别ID，考试ID
    questionTitle: '',
    questionAnswers: [[]],
    rightAnswers: [],
    parseContent: '',
  },
  images: {
    question1,
    question2,
    questionType1,
    questionType2,
  },
  rules: {
    questionTitle: [
      { required: true, message: "请输入题目标题", trigger: "blur" },
    ],
    parseContent: [
      { required: true, message: "请输入题目解析", trigger: "blur" },
    ]
  }
});
const { form, rules } = toRefs(data);
const currentAnswer = ref(form.value.questionAnswers[0])
const activeAnswerTab = ref('1')
const answerTab = ref(['1'])
watch(() => props.visible, value => {
  if (value) {
    if (props.detail.practiseId != null) {
      const questionAnswers = JSON.parse(props.detail.questionAnswers)
      const rightAnswers = JSON.parse(props.detail.rightAnswers)
      form.value = Object.assign({}, props.detail)
      form.value.questionAnswers = questionAnswers
      form.value.rightAnswers = rightAnswers
      if (form.value.questionType == '7') {
        form.value.questionType = '2'
      }
      answerTab.value = questionAnswers.map((i, index)=>`${index + 1}`)
    }
     currentAnswer.value = form.value.questionAnswers[0]
  } else {
    reset()
  }
})
/** 提交按钮 */
function submitForm() {
  proxy.$refs["questionRef"].validate(valid => {
    if (valid) {
      const params = JSON.parse(JSON.stringify(form.value))
      if (params.questionType == '2') {
        params.questionType = '7'
      }
      const rightAnswer = []
      for (let index = 0; index < params.questionAnswers.length; index++) {
        const element = params.questionAnswers[index];
        rightAnswer.push(element.filter(i => i.rightState).map(i => i.optionLabel))
      }
      params.rightAnswers = JSON.stringify(rightAnswer.flat())
      params.questionAnswers = JSON.stringify(params.questionAnswers)
      params.typeId = props.typeId
      params.practiseType = props.practiseType
      if (form.value.practiseId != null) {
        updatepractise(params).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          emits('finish')
        });
      } else {
        addpractise(params).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          emits('finish')
        });
      }
    }
  });
}
// 表单重置
function reset() {
  form.value = {
    questionType: '1',
    practiseType: '', //练习类型：c-章节 z-专项类别 k-历年考试
    questionTitle: '',
    questionAnswers: [[]],
    rightAnswers: [],
    parseContent: '',
  };
  currentAnswer.value = form.value.questionAnswers[0]
  activeAnswerTab.value = '1'
  answerTab.value = ['1']
  proxy.resetForm("questionRef");
}

// 添加题目的弹窗相关所有内用还记得咖啡贺卡顺丰航空
const questionTypeMap = {
  '1': "单选题",
  '2': "多空单选题",
};
function handleImport() {
  open.value = false
}

const handleTabChange = (value) => {
  currentAnswer.value = form.value.questionAnswers[Number(value) - 1]
}
const handleTabsEdit = (targetName, action) => {
  console.log("🚀 ~ handleTabsEdit ~ targetName, action:", targetName, action, activeAnswerTab.value)
  if (action === 'add') {
    answerTab.value.push(`${answerTab.value.length + 1}`)
    form.value.questionAnswers.push([])
    activeAnswerTab.value = `${answerTab.value.length}`
    answerTab.value = answerTab.value.map((item, index) => `${index + 1}`)
  } else if (action === 'remove') {
    if (answerTab.value.length === 1) {
      ElMessage.warning('至少要有一个答案')
      return
    }
    const tabs = answerTab.value
    let activeName = activeAnswerTab.value
    if (activeName === targetName) {
      tabs.forEach((tab, index) => {
        if (tab === targetName) {
          const nextTab = tabs[index + 1] || tabs[index - 1]
          if (nextTab) {
            activeName = nextTab
          }
        }
      })
    }
    activeAnswerTab.value = activeName
    form.value.questionAnswers.splice((Number(targetName) - 1), 1);
    answerTab.value = tabs.filter((tab) => tab !== targetName)
  }
}
// <!-- 题型;题目类型；1-单选，2-多选，3-判断;关联dict表中的code列，dict_key为question_type题目类型；1-单选，2-多选，3-判断; -->
const getQuestionType = (row) => {
  return questionTypeMap[row.questionType];
};
const getImageUrl = (isLevel = true, index) => {
  if (isLevel) {
    return data.images[`question${index}`];
  }
  return data.images[`questionType${index}`];
};

const AnswerFormRef = ref(null);
const handleAnswerUpdate = (item) => {
  const index = Number(activeAnswerTab.value) - 1
  form.value.questionAnswers[index] = item
  currentAnswer.value = item
}
const changeType = (type) => {
  if (form.value.questionType == `${type}`) {
    return
  }
  form.value.questionType = `${type}`;
  form.value.questionAnswers = [[]]
  currentAnswer.value = form.value.questionAnswers[0]
  activeAnswerTab.value = '1'
  answerTab.value = ['1']
  AnswerFormRef.value.changeType(`${type}`);
};

const addQuestionItem = () => {
  AnswerFormRef.value.addItem();
};
</script>
<style lang='scss' scoped>
@import './index.scss'
</style>